import 'dart:async';
import 'package:flutter/material.dart';

// ignore: must_be_immutable
class MyDialog extends Dialog {
  String title;
  String content;
  Function()? onClosed;

  MyDialog({
    super.key,
    required this.title,
    required this.onClosed,
    this.content = "",
  });

  _showTimer(context) {
    // 3S后关闭定时器
    Timer.periodic(Duration(milliseconds: 3000), (t) {
      print('关闭');
      Navigator.of(context).pop();
      t.cancel();
    });
    // print(t);
  }

  @override
  Widget build(BuildContext context) {
    _showTimer(context); // 调用定时器
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: Container(
          height: 300,
          width: 300,
          color: Colors.white,
          child: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(10),
                child: Stack(
                  children: <Widget>[
                    Align(
                      alignment: Alignment.center,
                      child: Text(title),
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: InkWell(
                        onTap: onClosed,
                        child: const Icon(Icons.close),
                      ),
                    )
                  ],
                ),
              ),
              const Divider(),
              Container(
                padding: const EdgeInsets.all(10),
                width: double.infinity,
                child: Text(content, textAlign: TextAlign.left),
              )
            ],
          ),
        ),
      ),
    );
  }
}

void myDialog(context) async {
  await showDialog(
      barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
      context: context,
      builder: (context) {
        return MyDialog(
            title: '标题',
            onClosed: () {
              print("关闭");
              Navigator.of(context).pop();
            },
            content: "我是一个内容");
      });
}
